<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Prometheus 自然语言查询</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1e40af',
                        secondary: '#3b82f6',
                        accent: '#60a5fa',
                        dark: '#1e293b',
                        light: '#f8fafc'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif']
                    }
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .bg-gradient-blue {
                background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            }
            .text-shadow {
                text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            .transition-all-300 {
                transition: all 300ms ease-in-out;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-gradient-blue text-white shadow-md">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-2">
                <i class="fa fa-line-chart text-2xl"></i>
                <h1 class="text-xl font-bold text-shadow">Prometheus 自然语言查询</h1>
            </div>
            <div class="text-sm">
                <span id="prometheus-url" class="bg-white/20 px-2 py-1 rounded">
                    <i class="fa fa-server mr-1"></i>
                    <span id="url-display">连接中...</span>
                </span>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-6">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 左侧查询区域 -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                        <i class="fa fa-search text-primary mr-2"></i>
                        自然语言查询
                    </h2>
                    
                    <div class="mb-4">
                        <label for="query-input" class="block text-sm font-medium text-gray-700 mb-1">
                            输入查询
                        </label>
                        <div class="relative">
                            <textarea 
                                id="query-input" 
                                class="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
                                rows="3"
                                placeholder="例如：过去5分钟内api_server的请求量"></textarea>
                            <div class="absolute right-2 bottom-2 text-xs text-gray-400">
                                <span id="char-count">0</span> 字符
                            </div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="time-range" class="block text-sm font-medium text-gray-700 mb-1">
                                时间范围
                            </label>
                            <select 
                                id="time-range" 
                                class="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                                <option value="5m">5分钟</option>
                                <option value="15m">15分钟</option>
                                <option value="30m">30分钟</option>
                                <option value="1h" selected>1小时</option>
                                <option value="6h">6小时</option>
                                <option value="12h">12小时</option>
                                <option value="24h">24小时</option>
                                <option value="7d">7天</option>
                            </select>
                        </div>
                        
                        <div>
                            <label for="graph-type" class="block text-sm font-medium text-gray-700 mb-1">
                                图表类型
                            </label>
                            <select 
                                id="graph-type" 
                                class="w-full border border-gray-300 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                                <option value="line" selected>折线图</option>
                                <option value="bar">柱状图</option>
                                <option value="area">面积图</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="flex justify-end">
                        <button 
                            id="query-button" 
                            class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-all-300 flex items-center">
                            <i class="fa fa-arrow-right mr-2"></i>
                            查询
                        </button>
                    </div>
                </div>
                
                <!-- 查询模板 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                        <i class="fa fa-bookmark text-primary mr-2"></i>
                        查询模板
                    </h2>
                    
                    <div id="templates-container" class="space-y-2">
                        <!-- 模板将通过JavaScript动态加载 -->
                        <div class="animate-pulse">
                            <div class="h-6 bg-gray-200 rounded w-3/4 mb-2"></div>
                            <div class="h-6 bg-gray-200 rounded w-full mb-2"></div>
                            <div class="h-6 bg-gray-200 rounded w-5/6"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 右侧结果区域 -->
            <div class="lg:col-span-2">
                <!-- 结果展示区域 -->
                <div class="bg-white rounded-lg shadow-md p-6 mb-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                        <i class="fa fa-bar-chart text-primary mr-2"></i>
                        查询结果
                    </h2>
                    
                    <div id="result-container">
                        <!-- 初始提示 -->
                        <div id="initial-prompt" class="text-center py-12 text-gray-500">
                            <i class="fa fa-info-circle text-4xl mb-4"></i>
                            <p>请在左侧输入自然语言查询并点击查询按钮</p>
                        </div>
                        
                        <!-- 加载中 -->
                        <div id="loading" class="hidden text-center py-12">
                            <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
                            <p class="mt-4 text-gray-600">正在处理查询...</p>
                        </div>
                        
                        <!-- 错误信息 -->
                        <div id="error" class="hidden bg-red-50 border border-red-200 rounded-lg p-4 text-red-700">
                            <div class="flex items-start">
                                <i class="fa fa-exclamation-circle text-xl mt-1 mr-3"></i>
                                <div>
                                    <h3 class="font-semibold">查询失败</h3>
                                    <p id="error-message"></p>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 成功结果 -->
                        <div id="success" class="hidden">
                            <!-- PromQL 查询 -->
                            <div class="mb-4">
                                <div class="flex justify-between items-center mb-1">
                                    <h3 class="text-sm font-medium text-gray-700">生成的 PromQL</h3>
                                    <button id="copy-promql" class="text-xs text-primary hover:text-primary/80 flex items-center">
                                        <i class="fa fa-copy mr-1"></i>
                                        复制
                                    </button>
                                </div>
                                <div id="promql-container" class="bg-gray-50 border border-gray-200 rounded-lg p-3 text-sm font-mono overflow-x-auto">
                                    <code id="promql-code"></code>
                                </div>
                            </div>
                            
                            <!-- 图表 -->
                            <div class="mb-4">
                                <h3 class="text-sm font-medium text-gray-700 mb-1">图表</h3>
                                <div class="bg-gray-50 border border-gray-200 rounded-lg p-4">
                                    <canvas id="result-chart" height="300"></canvas>
                                </div>
                            </div>
                            
                            <!-- 数据表格 -->
                            <div>
                                <div class="flex justify-between items-center mb-1">
                                    <h3 class="text-sm font-medium text-gray-700">数据</h3>
                                    <button id="export-data" class="text-xs text-primary hover:text-primary/80 flex items-center">
                                        <i class="fa fa-download mr-1"></i>
                                        导出
                                    </button>
                                </div>
                                <div class="overflow-x-auto">
                                    <table class="min-w-full bg-white border border-gray-200 rounded-lg">
                                        <thead>
                                            <tr id="table-header" class="bg-gray-50">
                                                <!-- 表头将通过JavaScript动态生成 -->
                                            </tr>
                                        </thead>
                                        <tbody id="table-body">
                                            <!-- 表格内容将通过JavaScript动态生成 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 历史记录 -->
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h2 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                        <i class="fa fa-history text-primary mr-2"></i>
                        历史查询
                    </h2>
                    
                    <div id="history-container" class="space-y-3">
                        <!-- 历史记录将通过JavaScript动态加载 -->
                        <div id="no-history" class="text-center py-6 text-gray-500">
                            <i class="fa fa-clock-o text-2xl mb-2"></i>
                            <p>暂无历史查询记录</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-4 mt-8">
        <div class="container mx-auto px-4 text-center text-sm">
            <p>© 2025 Prometheus 自然语言查询工具 | 使用 LangChain 和 Flask 构建</p>
        </div>
    </footer>

    <!-- JavaScript -->
    <script>
        // 全局变量
        let currentChart = null;
        
        // DOM 元素
        const queryInput = document.getElementById('query-input');
        const charCount = document.getElementById('char-count');
        const timeRange = document.getElementById('time-range');
        const graphType = document.getElementById('graph-type');
        const queryButton = document.getElementById('query-button');
        const initialPrompt = document.getElementById('initial-prompt');
        const loading = document.getElementById('loading');
        const error = document.getElementById('error');
        const errorMessage = document.getElementById('error-message');
        const success = document.getElementById('success');
        const promqlCode = document.getElementById('promql-code');
        const copyPromqlButton = document.getElementById('copy-promql');
        const resultChart = document.getElementById('result-chart');
        const exportDataButton = document.getElementById('export-data');
        const tableHeader = document.getElementById('table-header');
        const tableBody = document.getElementById('table-body');
        const historyContainer = document.getElementById('history-container');
        const noHistory = document.getElementById('no-history');
        const templatesContainer = document.getElementById('templates-container');
        const urlDisplay = document.getElementById('url-display');
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 更新字符计数
            updateCharCount();
            
            // 加载模板
            loadTemplates();
            
            // 加载历史记录
            loadHistory();
            
            // 更新Prometheus URL显示
            updatePrometheusUrlDisplay();
        });
        
        // 更新字符计数
        queryInput.addEventListener('input', updateCharCount);
        
        function updateCharCount() {
            const count = queryInput.value.length;
            charCount.textContent = count;
        }
        
        // 查询按钮点击事件
        queryButton.addEventListener('click', executeQuery);
        
        // 按Enter键执行查询
        queryInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                executeQuery();
            }
        });
        
        // 执行查询
        function executeQuery() {
            const query = queryInput.value.trim();
            
            if (!query) {
                showError('请输入查询语句');
                return;
            }
            
            // 显示加载状态
            showLoading();
            
            // 发送查询请求
            fetch('/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    query: query,
                    time_range: timeRange.value,
                    graph_type: graphType.value
                }),
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayResults(data);
                    loadHistory(); // 更新历史记录
                } else {
                    showError(data.error || '查询失败');
                }
            })
            .catch(error => {
                showError('网络错误，请稍后重试');
                console.error('Error:', error);
            });
        }
        
        // 显示加载状态
        function showLoading() {
            initialPrompt.classList.add('hidden');
            error.classList.add('hidden');
            success.classList.add('hidden');
            loading.classList.remove('hidden');
        }
        
        // 显示错误信息
        function showError(message) {
            loading.classList.add('hidden');
            errorMessage.textContent = message;
            error.classList.remove('hidden');
        }
        
        // 显示成功结果
        function displayResults(data) {
            loading.classList.add('hidden');
            
            // 设置PromQL
            promqlCode.textContent = data.promql;
            
            // 创建图表
            createChart(data.data);
            
            // 创建表格
            createTable(data.data);
            
            // 显示成功结果
            success.classList.remove('hidden');
        }
        
        // 创建图表
        function createChart(metricData) {
            // 销毁现有图表
            if (currentChart) {
                currentChart.destroy();
            }
            
            if (!metricData || metricData.length === 0) {
                return;
            }
            
            const ctx = resultChart.getContext('2d');
            
            // 准备数据
            const datasets = [];
            const labels = [];
            
            // 获取所有时间戳
            const allTimestamps = new Set();
            metricData.forEach(metric => {
                metric.values.forEach(point => {
                    allTimestamps.add(point[0]);
                });
            });
            
            // 排序时间戳
            const sortedTimestamps = Array.from(allTimestamps).sort((a, b) => a - b);
            
            // 创建标签（时间）
            sortedTimestamps.forEach(timestamp => {
                const date = new Date(timestamp * 1000);
                labels.push(date.toLocaleTimeString());
            });
            
            // 创建数据集
            const colors = [
                'rgba(59, 130, 246, 1)',   // 蓝色
                'rgba(16, 185, 129, 1)',   // 绿色
                'rgba(245, 158, 11, 1)',   // 橙色
                'rgba(239, 68, 68, 1)',    // 红色
                'rgba(139, 92, 246, 1)',   // 紫色
                'rgba(14, 165, 233, 1)',   // 天蓝色
                'rgba(249, 115, 22, 1)',   // 深橙色
                'rgba(236, 72, 153, 1)'    // 粉色
            ];
            
            metricData.forEach((metric, index) => {
                const colorIndex = index % colors.length;
                const color = colors[colorIndex];
                
                // 创建标签
                const metricName = metric.metric.__name__ || 'unknown_metric';
                const labels = [];
                for (const [key, value] of Object.entries(metric.metric)) {
                    if (key !== '__name__') {
                        labels.push(`${key}="${value}"`);
                    }
                }
                const label = labels.length > 0 ? `${metricName}{${labels.join(', ')}}` : metricName;
                
                // 创建数据点
                const data = [];
                sortedTimestamps.forEach(timestamp => {
                    const point = metric.values.find(p => p[0] === timestamp);
                    data.push(point ? parseFloat(point[1]) : null);
                });
                
                // 创建数据集配置
                const datasetConfig = {
                    label: label,
                    data: data,
                    borderColor: color,
                    backgroundColor: graphType.value === 'area' ? color.replace('1)', '0.2)') : color,
                    borderWidth: 2,
                    tension: 0.1,
                    fill: graphType.value === 'area'
                };
                
                // 根据图表类型调整配置
                if (graphType.value === 'bar') {
                    datasetConfig.type = 'bar';
                    datasetConfig.borderRadius = 4;
                    datasetConfig.maxBarThickness = 20;
                }
                
                datasets.push(datasetConfig);
            });
            
            // 创建图表
            currentChart = new Chart(ctx, {
                type: graphType.value === 'bar' ? 'bar' : 'line',
                data: {
                    labels: labels,
                    datasets: datasets
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false
                        }
                    },
                    scales: {
                        x: {
                            title: {
                                display: true,
                                text: '时间'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: '值'
                            },
                            beginAtZero: false
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    }
                }
            });
        }
        
        // 创建表格
        function createTable(metricData) {
            // 清空表格
            tableHeader.innerHTML = '';
            tableBody.innerHTML = '';
            
            if (!metricData || metricData.length === 0) {
                return;
            }
            
            // 创建表头
            const headerRow = document.createElement('tr');
            
            // 添加时间列
            const timeHeader = document.createElement('th');
            timeHeader.className = 'px-4 py-2 border-b text-left text-sm font-medium text-gray-700';
            timeHeader.textContent = '时间';
            headerRow.appendChild(timeHeader);
            
            // 添加指标列
            metricData.forEach(metric => {
                const metricName = metric.metric.__name__ || 'unknown_metric';
                const labels = [];
                for (const [key, value] of Object.entries(metric.metric)) {
                    if (key !== '__name__') {
                        labels.push(`${key}="${value}"`);
                    }
                }
                const label = labels.length > 0 ? `${metricName}{${labels.join(', ')}}` : metricName;
                
                const headerCell = document.createElement('th');
                headerCell.className = 'px-4 py-2 border-b text-left text-sm font-medium text-gray-700';
                headerCell.textContent = label;
                headerRow.appendChild(headerCell);
            });
            
            tableHeader.appendChild(headerRow);
            
            // 获取所有时间戳
            const allTimestamps = new Set();
            metricData.forEach(metric => {
                metric.values.forEach(point => {
                    allTimestamps.add(point[0]);
                });
            });
            
            // 排序时间戳
            const sortedTimestamps = Array.from(allTimestamps).sort((a, b) => a - b);
            
            // 创建表格行
            sortedTimestamps.forEach(timestamp => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50';
                
                // 添加时间单元格
                const timeCell = document.createElement('td');
                timeCell.className = 'px-4 py-2 border-b text-sm text-gray-600';
                const date = new Date(timestamp * 1000);
                timeCell.textContent = date.toLocaleString();
                row.appendChild(timeCell);
                
                // 添加指标值单元格
                metricData.forEach(metric => {
                    const cell = document.createElement('td');
                    cell.className = 'px-4 py-2 border-b text-sm text-gray-600';
                    
                    const point = metric.values.find(p => p[0] === timestamp);
                    cell.textContent = point ? parseFloat(point[1]).toFixed(4) : '-';
                    
                    row.appendChild(cell);
                });
                
                tableBody.appendChild(row);
            });
        }
        
        // 复制PromQL
        copyPromqlButton.addEventListener('click', () => {
            navigator.clipboard.writeText(promqlCode.textContent)
                .then(() => {
                    const originalText = copyPromqlButton.innerHTML;
                    copyPromqlButton.innerHTML = '<i class="fa fa-check mr-1"></i>已复制';
                    
                    setTimeout(() => {
                        copyPromqlButton.innerHTML = originalText;
                    }, 2000);
                })
                .catch(err => {
                    console.error('Failed to copy: ', err);
                });
        });
        
        // 导出数据
        exportDataButton.addEventListener('click', () => {
            // 在实际应用中，这里可以实现数据导出功能
            alert('数据导出功能将在后续版本中实现');
        });
        
        // 加载历史记录
        function loadHistory() {
            fetch('/history')
                .then(response => response.json())
                .then(data => {
                    const history = data.history || [];
                    
                    if (history.length === 0) {
                        noHistory.classList.remove('hidden');
                        return;
                    }
                    
                    noHistory.classList.add('hidden');
                    
                    // 清空历史记录容器
                    while (historyContainer.firstChild) {
                        if (historyContainer.firstChild === noHistory) {
                            break;
                        }
                        historyContainer.removeChild(historyContainer.firstChild);
                    }
                    
                    // 添加历史记录
                    history.forEach((item, index) => {
                        const historyItem = document.createElement('div');
                        historyItem.className = 'bg-gray-50 border border-gray-200 rounded-lg p-3 hover:bg-gray-100 transition-all-300 cursor-pointer';
                        
                        historyItem.innerHTML = `
                            <div class="flex justify-between items-start">
                                <div class="flex-1">
                                    <p class="text-sm font-medium text-gray-800">${item.query}</p>
                                    <div class="mt-1 text-xs text-gray-500 truncate">
                                        <code>${item.promql}</code>
                                    </div>
                                </div>
                                <div class="ml-2 flex flex-col items-end">
                                    <span class="text-xs text-gray-400">${item.timestamp}</span>
                                    <button class="reuse-history mt-1 text-xs text-primary hover:text-primary/80" data-index="${index}">
                                        <i class="fa fa-refresh mr-1"></i>复用
                                    </button>
                                </div>
                            </div>
                        `;
                        
                        historyContainer.appendChild(historyItem);
                        
                        // 添加复用事件
                        const reuseButton = historyItem.querySelector('.reuse-history');
                        reuseButton.addEventListener('click', (e) => {
                            e.stopPropagation();
                            reuseHistoryItem(index);
                        });
                        
                        // 点击历史记录项也可以复用
                        historyItem.addEventListener('click', () => {
                            reuseHistoryItem(index);
                        });
                    });
                })
                .catch(error => {
                    console.error('Error loading history:', error);
                });
        }
        
        // 复用历史记录
        function reuseHistoryItem(index) {
            fetch(`/history/${index}`, {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    queryInput.value = data.query;
                    updateCharCount();
                    
                    // 滚动到查询区域
                    queryInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    
                    // 聚焦查询输入框
                    queryInput.focus();
                }
            })
            .catch(error => {
                console.error('Error reusing history:', error);
            });
        }
        
        // 加载模板
        function loadTemplates() {
            fetch('/templates')
                .then(response => response.json())
                .then(data => {
                    const templates = data.templates || [];
                    
                    // 清空模板容器
                    templatesContainer.innerHTML = '';
                    
                    // 添加模板
                    templates.forEach(template => {
                        const templateItem = document.createElement('div');
                        templateItem.className = 'bg-gray-50 border border-gray-200 rounded-lg p-3 hover:bg-gray-100 transition-all-300 cursor-pointer';
                        
                        templateItem.innerHTML = `
                            <div class="flex justify-between items-center">
                                <span class="text-sm font-medium text-gray-800">${template.name}</span>
                                <i class="fa fa-chevron-right text-xs text-gray-400"></i>
                            </div>
                            <p class="mt-1 text-sm text-gray-600">${template.query}</p>
                        `;
                        
                        templatesContainer.appendChild(templateItem);
                        
                        // 添加点击事件
                        templateItem.addEventListener('click', () => {
                            queryInput.value = template.query;
                            updateCharCount();
                            
                            // 滚动到查询区域
                            queryInput.scrollIntoView({ behavior: 'smooth', block: 'center' });
                            
                            // 聚焦查询输入框
                            queryInput.focus();
                        });
                    });
                })
                .catch(error => {
                    console.error('Error loading templates:', error);
                });
        }
        
        // 更新Prometheus URL显示
        function updatePrometheusUrlDisplay() {
            // 在实际应用中，这里可以从配置中获取Prometheus URL
            const prometheusUrl = 'http://localhost:9090';
            urlDisplay.textContent = prometheusUrl;
        }
    </script>
</body>
</html>
